<template>
  <!-- <transition name="el-zoom-in-center"> -->

  <div class="jsbos-preview-main">
    <div class="jsbos-common-page-header">
      <el-page-header
        @back="goBack"
        :content="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'"
      />

      <div class="options">
        <el-button v-if="active == 1" @click="lastSetp" type="primary"
          >上一步</el-button
        >
        <el-button v-if="active == 0" @click="next" type="primary"
          >下一步</el-button
        >
        <el-button v-if="active == 1" @click="dataFormSubmit" type="primary"
          >保存</el-button
        >
        <el-button v-if="active == 1" @click="saveAndPublish" type="primary"
          >发布</el-button
        >
        <el-button @click="goBack"> 取 消 </el-button>
      </div>
    </div>

    <el-row
      :gutter="15"
      class="main"
      :style="{
        margin: '0 auto',
        width: '1100px',
        height: '454px',
        overflow: 'hidden',
      }"
    >
      <el-steps
        finish-status="success"
        simple
        :active="active"
        style="width: 1000px; margin: 0 auto; position: relative"
      >
        <el-step title="基础信息"></el-step>
        <el-step title="设定坐标"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="elForm"
        :model="dataForm"
        :rules="rules"
        size="small"
        label-width="100px"
        label-position="right"
        v-show="active == 0"
      >
        <template v-if="!loading">
          <el-col :span="24">
            <el-form-item label-width="0">
              <groupTitle
                content-position="left"
                content="基础信息"
              ></groupTitle>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="dataForm.name"
                placeholder="请输入"
                clearable
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select
                v-model="dataForm.categoryId"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in categoryIdOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.enCode"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期" prop="expiredType">
              <el-radio-group v-model="dataForm.expiredType" size="small">
                <el-radio
                  v-for="(item, index) in expiredTypeOptions"
                  :key="index"
                  :label="item.id"
                  :disabled="item.disabled"
                  >{{ item.fullName }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dataForm.expiredType == '0'">
            <el-form-item label="有效期时长" prop="expiredDay">
              <el-input-number
                v-model="dataForm.expiredDay"
                placeholder="数字文本"
                :step="1"
                min="30"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="证书介绍" prop="description">
              <el-input
                v-model="dataForm.description"
                placeholder="请输入证书介绍"
                style="width: 100%"
                true
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效标志" prop="enabledMark">
              <el-radio-group v-model="dataForm.enabledMark" size="small">
                <el-radio
                  v-for="(item, index) in enabledMarkOptions"
                  :key="index"
                  :label="item.id"
                  :disabled="item.disabled"
                  >{{ item.fullName }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0">
              <groupTitle
                content-position="left"
                content="设置坐标"
              ></groupTitle>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="证书图片" prop="cover">
              <div style="display: flex; flex-direction: row">
                <img
                  :src="define.comUrl + dataForm.cover.url"
                  class="el-upload-list__item-thumbnail"
                  :z-index="10000"
                  ref="image"
                  fit="cover"
                  style="height: 100px; width: 160px"
                />
                <div
                  style="margin-left: 20px; line-height: 22px; font-weight: 200"
                >
                  <el-button type="primary" @click="openUploadDialog">
                    上传图片
                  </el-button>
                  <div
                    style="color: #8c8c8c; margin-top: 3px"
                    data-v-0796f1a5=""
                  >
                    封面将按16:9显示
                  </div>
                  <div style="color: #8c8c8c" data-v-0796f1a5="">
                    最佳分辨率：570*322
                  </div>
                  <div style="color: #8c8c8c" data-v-0796f1a5="">
                    支持格式：jpg、jpeg、png
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </template>
      </el-form>

      <div class="box" v-if="active == 1">
        <groupTitle content-position="left" content="设置坐标"></groupTitle>
        <div class="top" style>
          <p style="font-size: 15px; float: left">
            请勾选字段并拖到相应的位置：
          </p>
          <el-checkbox-group
            v-model="checkList"
            style="margin-left: 20px; float: left"
            @change="change"
          >
            <el-checkbox
              v-for="item in dataForm.fieldConfig"
              :label="item.name"
              :checked="item.isShow"
              :key="item.id"
            ></el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="editer">
          <div
            class="canvasBox"
            style="width: 810px; float: left"
            ref="canvasBox"
          >
            <img
              :src="define.APIURl + dataForm.cover.url"
              alt
              style="width: 810px"
            />

            <div
              class="text"
              @mousedown="mousedown($event, item)"
              v-for="item in dataForm.fieldConfig"
              :style="{
                ...item.cssObj,
                fontSize: item.cssObj.fontSize + 'px',
                transform: `scale( ${item.transform ? item.transform : 1}) `,
              }"
              v-if="item.isShow"
              :key="item.id"
            >
              <span v-if="item.id != '6'"> {{ item.defaultText }} </span>

              <div class="circle-seal" v-if="item.id == '6'" ref="circleSeal">
                <svg viewBox="0 0 140 140">
                  <path d="M 20,70 a 50,50 0 1,1 0,1 z" id="circle-seal" />
                  <text>
                    <textPath xlink:href="#circle-seal">
                      {{ item.defaultText }}
                    </textPath>
                  </text>
                </svg>
                <div class="star">★</div>
                <!-- <div class="text">权威鉴定</div> -->
              </div>
            </div>
          </div>

          <div class="cortol" v-if="chooseItem.cssObj">
            <div slot="header" class="clearfix">
              <groupTitle
                content-position="left"
                :content="chooseItem.name"
              ></groupTitle>
            </div>
            <div class="cortolItem">
              字体颜色：
              <el-color-picker
                v-model="chooseItem.cssObj.color"
              ></el-color-picker>
            </div>
            <div class="cortolItem">
              字体大小：
              <el-input-number
                v-model="chooseItem.cssObj.fontSize"
                :min="1"
                :max="50"
                label="字体大小："
                style="width: 120px"
              ></el-input-number>
              <!-- <input type="text" v-model="chooseItem.cssObj.fontSize" style="width: 50px;" /> -->
            </div>
            <div class="cortolItem">
              字体粗细：
              <el-input-number
                v-model="chooseItem.cssObj.fontWeight"
                :min="100"
                :max="1000"
                :step="100"
                label="字体粗细："
                style="width: 120px"
              ></el-input-number>
            </div>

            <div class="cortolItem" v-if="chooseItem.name == '公章'">
              印章大小：
              <el-input-number
                v-model="chooseItem.transform"
                :min="0"
                :max="3"
                :step="0.1"
                label="大小："
                style="width: 120px"
              ></el-input-number>
            </div>

            <div class="cortolItem">
              文字：
              <el-input
                v-model="chooseItem.defaultText"
                :step="1"
                label="文字"
                style="width: 120px"
              ></el-input>
            </div>
            <!-- <div class="cortolItem">
            字体颜色：  <el-color-picker v-model="color1"></el-color-picker>
            </div>-->
          </div>
        </div>
      </div>
    </el-row>

    <SelectCover
      v-if="selectCoverVisible"
      ref="selectCoverRef"
      @selectComplete="selectCover"
    >
    </SelectCover>
  </div>

  <!-- </transition> -->
</template>
<script>
import request from "@/utils/request";
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";
import { overlayMode } from "codemirror";
import SelectCover from "@/views/tems/course/cover/Form";

export default {
  components: { SelectCover },

  props: [],
  data() {
    return {
      checkList: [],
      active: 0,
      imgBi: 1,
      selectCoverVisible: false,
      visible: false,
      loading: false,
      isDetail: false,
      chooseItem: {},
      boxRect: {},
      dataForm: {
        id: "",
        name: "",
        categoryId: "",
        expiredType: "1",
        expiredDay: 1,
        description: "",
        enabledMark: "1",
        creatorUserId: "",
        creatorTime: "",
        cover: { url: "" },
        fieldConfig: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        expiredType: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        enabledMark: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
      },
      categoryIdOptions: [],
      expiredTypeOptions: [
        { fullName: "永久有效", id: "1" },
        { fullName: "有效周期", id: "0" },
      ],
      enabledMarkOptions: [
        { fullName: "待发布", id: "0" },
        { fullName: "已发布", id: "1" },
      ],
      thumbLeft: 0,
      thumbW: 0,
      thumbTop: 0,
      thumbH: 0,
    };
  },
  computed: {},
  // watch: {
  //   thumbLeft(new,old) {

  //   },
  //   thumbTop(new,old) {

  //   },

  // },
  created() {
    this.getCategoryIdOptions();
  },
  mounted() {},
  methods: {
    getImageSize(url) {
      console.log(" this,imgBi", url);
      var img = new Image();
      img.onload = () => {
        this.imgBi = img.width / 810;

        img = null;
      };

      img.src = url;
    },

    selectCover(coverUlr, data) {
      this.dataForm.cover = JSON.parse(data);
    },
    openUploadDialog() {
      this.selectCoverVisible = true;
      this.$nextTick(() => {
        this.$refs.selectCoverRef.initData();
      });
    },
    setBoxRect() {
      this.boxRect = this.$refs.canvasBox.getBoundingClientRect();
    },
    mousedown(event, item) {
      this.chooseItem = item;
      this.setBoxRect();
      // 判断是否是鼠标左键
      if (event.button !== 0) return;

      this.thumbLeft = event.target.offsetLeft;
      this.thumbTop = event.target.offsetTop;
      this.thumbW = event.target.offsetWidth;
      this.thumbLeft = event.target.offsetHeight;
      // this.thumbLeft =
      document.addEventListener("mousemove", this.mousemove);
      document.addEventListener("mouseup", this.mouseup);
    },
    mousemove(event) {
      event.preventDefault();
      event.stopPropagation();

      this.thumbLeft = event.clientX - this.thumbW / 2 - this.boxRect.left;
      this.thumbTop = event.clientY - this.thumbH / 2 - this.boxRect.top;

      this.chooseItem.cssObj.top = this.thumbTop + "px";
      this.chooseItem.cssObj.left = this.thumbLeft + "px";

      this.chooseItem.x = this.thumbLeft * this.imgBi;
      this.chooseItem.y = this.thumbTop * this.imgBi;
      this.setLimit();
    },
    setLimit() {
      const thumbRight = this.thumbLeft + this.thumbW;
      const thumbBottom = this.thumbTop + this.thumbH;
      if (this.thumbLeft <= 0) {
        this.thumbLeft = 0;

        this.chooseItem.cssObj.left = this.thumbLeft + "px";

        this.chooseItem.x = this.thumbLeft * this.imgBi;
      }
      if (this.thumbTop <= 0) {
        this.thumbTop = 0;
        this.chooseItem.cssObj.top = this.thumbTop + "px";
        this.chooseItem.y = this.thumbTop * this.imgBi;
      }
      if (thumbRight >= this.boxRect.width) {
        this.thumbLeft = this.boxRect.width - this.thumbW;
        this.chooseItem.cssObj.left = this.thumbLeft + "px";
        this.chooseItem.x = this.thumbLeft * this.imgBi;
      }
      if (thumbBottom >= this.boxRect.height) {
        this.thumbTop = this.boxRect.height - this.thumbH;
        this.chooseItem.cssObj.top = this.thumbTop + "px";
        this.chooseItem.y = this.thumbTop * this.imgBi;
      }
    },
    mouseup() {
      this.removeMouseEvent();
    },
    removeMouseEvent() {
      document.removeEventListener("mousemove", this.mousemove);
      document.removeEventListener("mouseup", this.mouseup);
    },

    choose(item) {
      this.chooseItem = item;
    },
    change(v) {
      this.dataForm.fieldConfig.forEach((ele) => {
        var idx = v.findIndex((el) => {
          return el == ele.name;
        });
        if (idx != -1) {
          ele.isShow = true;
        } else {
          ele.isShow = false;
        }
      });
    },
    lastSetp() {
      this.active--;
    },
    next() {
      this.active++;
      console.log(this.active);
      if (this.active == 1) {
        this.getImageSize(this.define.comUrl + this.dataForm.cover.url);
      }
    },
    saveAndPublish() {
      this.dataForm.enabledMark = "1";
      this.dataFormSubmit();
    },
    getCategoryIdOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "CertificateCategory",
        })
        .then((res) => {
          this.categoryIdOptions = res;
        });
    },
    goBack() {
      this.$emit("refresh");
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
      this.dataForm.expiredType = "1";
      this.dataForm.enabledMark = "1";
    },
    init(id, isDetail) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.isDetail = isDetail || false;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          request({
            url: "/api/course/TemsCert/" + this.dataForm.id,
            method: "get",
          }).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.dataForm.fieldConfig = [
            {
              id: 1,
              name: "用户姓名",
              cssObj: {
                top: "30px",
                left: "30px",
                fontSize: 18,
                color: "#000000",
                fontWeight: 400,
              },
              x: 0,
              y: 0,
              isShow: false,
              defaultText: "<用户姓名>",
            },
            {
              id: 2,
              name: "身份证号",
              cssObj: {
                top: "50px",
                left: "30px",
                fontSize: 18,
                color: "#000000",
                fontWeight: 400,
              },
              x: 0,
              y: 0,
              isShow: false,
              defaultText: "<41012345678901>",
            },
            {
              id: 3,
              name: "任务名称",
              cssObj: {
                top: "80px",
                left: "30px",
                fontSize: 18,
                color: "#000000",
                fontWeight: 400,
              },
              x: 0,
              y: 0,
              isShow: false,
              defaultText: "<任务名称>",
            },
            {
              id: 4,
              name: "获证时间",
              cssObj: {
                top: "110px",
                left: "30px",
                fontSize: 18,
                color: "#000000",
                fontWeight: 400,
              },
              x: 0,
              y: 0,
              isShow: false,
              defaultText: "<获证时间>",
            },
            {
              id: 5,
              name: "证书编号",
              cssObj: {
                top: "150px",
                left: "30px",
                fontSize: 18,
                color: "#000000",
                fontWeight: 400,
              },
              x: 0,
              y: 0,
              isShow: false,
              defaultText: "<证书编号>",
            },
            {
              id: 6,
              name: "公章",
              cssObj: {
                top: "30px",
                left: "30px",
                fontSize: 20,
                color: "#FF0000",
                fontWeight: 900,
              },
              x: 0,
              y: 0,
              r: 0,
              transform: 1,
              isShow: false,
              defaultText: "顺利结业凭证",
            },
            {
              id: 7,
              name: "成绩",
              cssObj: {
                top: "210px",
                left: "30px",
                fontSize: 18,
                color: "#000000",
                fontWeight: 400,
              },
              x: 0,
              y: 0,
              isShow: false,
              defaultText: "<成绩>",
            },
          ];
          // this.clearData(this.dataForm);
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          this.request();
        }
      });
    },
    request() {
      var _data = this.dataList();

      if (!this.dataForm.id) {
        request({
          url: "/api/course/TemsCert",
          method: "post",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      } else {
        request({
          url: "/api/course/TemsCert/" + this.dataForm.id,
          method: "PUT",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      var circleSeal = _data.fieldConfig.find((el) => {
        return el.id == 6;
      });

      if (circleSeal.isShow) {
        let r = (140 * circleSeal.transform) / 2;
        circleSeal.x = circleSeal.x + r;
        circleSeal.y = circleSeal.x + r;
        circleSeal.r = r;
      }

      _data.cover = JSON.stringify(_data.cover);
      _data.fieldConfig = JSON.stringify(_data.fieldConfig);
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.cover = JSON.parse(_dataAll.cover);

      _dataAll.fieldConfig = JSON.parse(_dataAll.fieldConfig);
      this.dataForm = _dataAll;
    },
  },
};
</script>
<style lang="scss" scoped>
.circle-seal {
  width: 140px;
  height: 140px;
  // margin: 100px auto 0;
  // font-size: 22px;
  // font-weight: bold;
  // background-color: #ffffff;
  position: absolute;
  border-radius: 50%;
  border: 1px solid red;
  // box-shadow: 0 0 0 22px #ffffff, 0 0 0 24px red;
}

.star {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  line-height: 100%;
  font-size: 70px;
  // border-radius: 50%;
  color: red;
}

.circle-seal path {
  fill: none;
}

.circle-seal svg {
  display: block;
  overflow: visible;
  transform: rotate(-26deg);
}

.circle-seal svg text {
  letter-spacing: 2px;
  fill: red;
}

.circle-seal .text {
  color: red;
  // font-size: 18px;
  position: absolute;
  top: 83px;
  left: 14px;
}

.cortol {
  width: 200px;

  line-height: 40px;
  float: right;
}

.editer {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
  width: 1060px;

  background-color: #fafafa;
  position: relative;

  .canvasBox {
    position: relative;
    -webkit-user-drag: none;
    /* 禁用Webkit内核浏览器的拖动效果 */
    -moz-user-drag: none;
    /* 禁用Firefox的拖动效果 */
    user-select: none;
    /* 禁止选中图片 */
    -webkit-tap-highlight-color: transparent;
    /* 在iOS上禁止点击高亮效果 */

    overflow: hidden;
  }

  img {
    width: 810px;

    -webkit-user-drag: none;
    /* 禁用Webkit内核浏览器的拖动效果 */
    -moz-user-drag: none;
    /* 禁用Firefox的拖动效果 */
    user-select: none;
    /* 禁止选中图片 */
    -webkit-tap-highlight-color: transparent;
    /* 在iOS上禁止点击高亮效果 */
  }

  .text {
    cursor: move;
    position: absolute;
  }
}
</style>
